<template>
  <div class="schedule-management">
    <h1>Doctor Schedule Management</h1>
    <el-card class="box-card">
      <div class="card-header">
        <el-button type="primary" @click="dialogVisible = true">Add New Schedule</el-button>
        <el-input
          v-model="searchQuery"
          placeholder="Search doctor name or department..."
          style="width: 300px; margin-left: 16px;"
          clearable
        />
      </div>
      
      <el-table :data="filteredSchedules" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="Doctor" width="150">
          <template #default="scope">
            {{ scope.row.doctorName }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="Department" width="150" />
        <el-table-column label="Date" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.scheduleDate) }}
          </template>
        </el-table-column>
        <el-table-column label="Start Time" width="120">
          <template #default="scope">
            {{ formatTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="End Time" width="120">
          <template #default="scope">
            {{ formatTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="maxPatients" label="Max Patients" width="120" />
        <el-table-column prop="currentPatients" label="Current Patients" width="120" />
        <el-table-column label="Operations" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">Edit</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredSchedules.length"
        class="pagination"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? 'Edit Schedule' : 'Add New Schedule'"
      width="50%"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="Doctor" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="Select doctor" filterable @change="onDoctorChange">
            <el-option 
              v-for="doctor in doctors" 
              :key="doctor.id" 
              :label="doctor.name" 
              :value="doctor.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Department" prop="department">
          <el-input v-model="form.department" disabled />
        </el-form-item>
        <el-form-item label="Date" prop="scheduleDate">
          <el-date-picker 
            v-model="form.scheduleDate" 
            type="date" 
            placeholder="Select date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disablePastDates"
          />
        </el-form-item>
        <el-form-item label="Start Time" prop="startTime">
          <el-time-picker 
            v-model="form.startTime" 
            format="HH:mm"
            value-format="HH:mm"
            placeholder="Select start time" 
          />
        </el-form-item>
        <el-form-item label="End Time" prop="endTime">
          <el-time-picker 
            v-model="form.endTime" 
            format="HH:mm"
            value-format="HH:mm"
            placeholder="Select end time" 
          />
        </el-form-item>
        <el-form-item label="Max Patients" prop="maxPatients">
          <el-input-number v-model="form.maxPatients" :min="1" :step="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitForm">Save</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useScheduleStore } from '../../stores/schedule'
import { useUserStore } from '../../stores/users'
import dayjs from 'dayjs'

const scheduleStore = useScheduleStore()
const userStore = useUserStore()

const schedules = ref([])
const doctors = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  id: null,
  doctorId: null,
  doctorName: '',
  department: '',
  scheduleDate: dayjs().format('YYYY-MM-DD'),
  startTime: '08:30',
  endTime: '17:30',
  maxPatients: 20,
  currentPatients: 0
})

const rules = {
  doctorId: [{ required: true, message: 'Please select a doctor', trigger: 'change' }],
  scheduleDate: [{ required: true, message: 'Please select a date', trigger: 'change' }],
  startTime: [{ required: true, message: 'Please select start time', trigger: 'change' }],
  endTime: [{ required: true, message: 'Please select end time', trigger: 'change' }],
  maxPatients: [{ required: true, message: 'Please enter maximum patients', trigger: 'blur' }]
}

const filteredSchedules = computed(() => {
  const query = searchQuery.value.toLowerCase().trim()
  if (!query) return schedules.value
  
  return schedules.value.filter(schedule => 
    schedule.doctorName.toLowerCase().includes(query) ||
    schedule.department.toLowerCase().includes(query)
  )
})

onMounted(async () => {
  await Promise.all([
    fetchSchedules(),
    fetchDoctors()
  ])
})

async function fetchSchedules() {
  try {
    const response = await scheduleStore.getSchedules()
    schedules.value = response
  } catch (error) {
    ElMessage.error('Failed to load schedules')
  }
}

async function fetchDoctors() {
  try {
    const response = await userStore.getDoctors()
    doctors.value = response
  } catch (error) {
    ElMessage.error('Failed to load doctors')
  }
}

function onDoctorChange(doctorId) {
  const selectedDoctor = doctors.value.find(doctor => doctor.id === doctorId)
  if (selectedDoctor) {
    form.value.doctorName = selectedDoctor.name
    form.value.department = selectedDoctor.department
  }
}

function handleEdit(row) {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

async function handleDelete(id) {
  try {
    await ElMessageBox.confirm('Are you sure you want to delete this schedule?', 'Warning', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    })
    
    await scheduleStore.deleteSchedule(id)
    ElMessage.success('Schedule deleted successfully')
    await fetchSchedules()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete schedule')
    }
  }
}

async function submitForm() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await scheduleStore.updateSchedule(form.value)
          ElMessage.success('Schedule updated successfully')
        } else {
          await scheduleStore.createSchedule(form.value)
          ElMessage.success('Schedule added successfully')
        }
        
        dialogVisible.value = false
        await fetchSchedules()
        resetForm()
      } catch (error) {
        ElMessage.error(isEdit.value ? 'Failed to update schedule' : 'Failed to add schedule')
      }
    }
  })
}

function resetForm() {
  form.value = {
    id: null,
    doctorId: null,
    doctorName: '',
    department: '',
    scheduleDate: dayjs().format('YYYY-MM-DD'),
    startTime: '08:30',
    endTime: '17:30',
    maxPatients: 20,
    currentPatients: 0
  }
  isEdit.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD')
}

function formatTime(timeString) {
  return timeString
}

function disablePastDates(date) {
  return date < dayjs().subtract(1, 'day')
}
</script>

<style scoped>
.schedule-management {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 